package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String url = request.getRequestURI();
        if (url.contains("login")){
            log.info("登录请求: {}", url);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = request.getHeader("token");
        if (token == null  || token.isEmpty()){
            log.info("token为空");
            response.setStatus(401);
            return;
        }

        try
            {

                Claims claims = JwtUtils.parseToken(token);
                Integer userId =  claims.get("id", Integer.class);
                log.info("当前用户id,存入ThreadLocal");
                CurrentUserHoler.setCurrentUser(userId);
            } catch (Exception e) {

            log.info("token解析失败");
            response.setStatus(401);
            return;

        }
        filterChain.doFilter(servletRequest, servletResponse);

        log.info("删除ThreadLocal中的登录信息");
        CurrentUserHoler.removeCurrentUser();

    }
}
